<template>
  <div class="member-container">
	  <el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	          <el-col :span="24" class="text-center">
	              <div class="title-wrapper">
	              <i class="el-icon-search el-icon--large"></i>
	              <h1 class="main-title">住户信息管理系统</h1>
	              <p class="sub-title">以细致管理留存住户心声，用贴心服务传递社区温度，让每一份信息都成为连接信任的桥梁</p>
	              </div>
	          </el-col>
	      </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="成员详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="成员信息" direction="vertical" :column="4" :model="userMessage" border>
        <el-descriptions-item label="ID" :span="2">{{ userMessage.id }}</el-descriptions-item>
        <el-descriptions-item label="账号ID" :span="2">{{ userMessage.accountId }}</el-descriptions-item>
        <el-descriptions-item label="姓名" :span="2">{{ userMessage.name }}</el-descriptions-item>
        <el-descriptions-item label="性别" :span="2">{{ userMessage.gender === 'M' ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="个人照片" :span="2">
          <el-image 
            v-if="userMessage.photo" 
            :src="getPhotoUrl(userMessage.photo)" 
            style="width: 100px; height: 100px" 
            fit="cover"
          ></el-image>
          <span v-else>无照片</span>
        </el-descriptions-item>
        <el-descriptions-item label="居住地" :span="2">{{ userMessage.property }}</el-descriptions-item>
        <el-descriptions-item label="出生日期" :span="2">{{ formatDate(userMessage.birthDate) }}</el-descriptions-item>
        <el-descriptions-item label="身份证" :span="2">{{ userMessage.identityNumber }}</el-descriptions-item>
        <el-descriptions-item label="联系方式" :span="2">{{ userMessage.contactInfo }}</el-descriptions-item>
        <el-descriptions-item label="职业" :span="2">{{ userMessage.occupation }}</el-descriptions-item>
        <el-descriptions-item label="角色" :span="2">{{ userMessage.memberType }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ userMessage.remarks }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">{{ userMessage.status }}</el-descriptions-item>
        <el-descriptions-item label="创建日期" :span="2">{{ formatDate(userMessage.createdAt) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑成员"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <!-- 基本信息部分 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名（可选修改）" prop="name">
              <el-input v-model="ruleForm.name" placeholder="不填则保持原姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别（可选修改）" prop="gender">
              <el-radio-group v-model="ruleForm.gender">
                <el-radio :label="'M'">男</el-radio>
                <el-radio :label="'F'">女</el-radio>
              </el-radio-group>
              <div class="form-hint">不选择则保持原性别</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账号ID（可选修改）" prop="accountId">
              <el-input v-model="ruleForm.accountId" type="number" placeholder="不填则保持原账号ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="个人照片（可选更新）">
              <el-upload
                action=""
                :show-file-list="false"
                :on-change="handlePhotoChange"
                accept="image/*"
              >
                <el-button size="small" type="primary">上传新照片</el-button>
              </el-upload>
              <div class="form-hint">不上传则保持原照片</div>
              <!-- 预览当前照片 -->
              <el-image 
                v-if="ruleForm.photo || ruleForm.originalPhoto" 
                :src="getPhotoUrl(ruleForm.photo || ruleForm.originalPhoto)" 
                style="width: 80px; height: 80px; margin-top: 10px" 
                fit="cover"
              ></el-image>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="房产（可选修改）" prop="property">
              <el-input v-model="ruleForm.property" placeholder="不填则保持原地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期（可选修改）" prop="birthDate">
              <el-date-picker
                v-model="ruleForm.birthDate"
                type="date"
                placeholder="不选择则保持原日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证（可选修改）" prop="identityNumber">
              <el-input v-model="ruleForm.identityNumber" placeholder="不填则保持原身份证号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系方式部分 -->
        <el-divider></el-divider>
        <el-form-item label="联系方式（可选修改）" prop="contactInfo">
          <el-input v-model="ruleForm.contactInfo" placeholder="不填则保持原手机号"></el-input>
        </el-form-item>

        <!-- 职业与状态部分 -->
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职业（可选修改）" prop="occupation">
              <el-input v-model="ruleForm.occupation" placeholder="不填则保持原职业"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态（可选修改）" prop="status">
              <el-select v-model="ruleForm.status" placeholder="不选择则保持原状态">
                <el-option label="活跃" value="Active"></el-option>
                <el-option label="非活跃" value="InActive"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色（可选修改）" prop="memberType">
              <el-input v-model="ruleForm.memberType" placeholder="不填则保持原角色"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注（可选修改）" prop="remarks">
              <el-input v-model="ruleForm.remarks" placeholder="不填则保持原备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="formSubmit()">确 定</el-button>
            <el-button @click="dialogVisible1 = false">取 消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="dialogVisible2"
      title="添加成员"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="addRules" 
        ref="addFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <!-- 基本信息部分 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="addForm.gender">
                <el-radio :label="'M'">男</el-radio>
                <el-radio :label="'F'">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账号ID（可选）" prop="accountId">
              <el-input v-model="addForm.accountId" type="number" placeholder="请输入关联的账号ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="个人照片（可选）">
              <el-upload
                action=""
                :show-file-list="false"
                :on-change="handleAddPhotoChange"
                accept="image/*"
              >
                <el-button size="small" type="primary">上传照片</el-button>
              </el-upload>
              <el-image 
                v-if="addForm.photo" 
                :src="addForm.photo" 
                style="width: 80px; height: 80px; margin-top: 10px" 
                fit="cover"
              ></el-image>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="房产（可选）" prop="property">
              <el-input v-model="addForm.property"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期（可选）" prop="birthDate">
              <el-date-picker
                v-model="addForm.birthDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="identityNumber">
              <el-input v-model="addForm.identityNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系方式部分 -->
        <el-divider></el-divider>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="addForm.contactInfo"></el-input>
        </el-form-item>

        <!-- 职业与状态部分 -->
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职业（可选）" prop="occupation">
              <el-input v-model="addForm.occupation"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="addForm.status" placeholder="请选择">
                <el-option label="活跃" value="Active"></el-option>
                <el-option label="非活跃" value="InActive"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色（可选）" prop="memberType">
              <el-input v-model="addForm.memberType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注（可选）" prop="remarks">
              <el-input v-model="addForm.remarks"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="addSubmit()">确 定</el-button>
            <el-button @click="dialogVisible2 = false">取 消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 搜索和操作区 -->
    <el-row :gutter="20" style="width: 100%; margin-bottom: 20px;">
      <el-col :span="12">
        <el-input 
          placeholder="请输入姓名查询" 
          v-model="searchQuery1" 
          style="width: 70%;"
          @keyup.enter="handleSearch"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch()" style="margin-left: 10px;">搜索</el-button>
      </el-col>
      <el-col :span="12" class="text-right">
        <el-button type="primary" icon="el-icon-plus" @click="openDetails2()">添加</el-button>
      </el-col>
    </el-row>

    <!-- 表格部分 -->
    <el-table 
      :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
      border 
      style="width: 100%"
      height="450"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="id" label="ID" width="100" align="center"></el-table-column>
      <el-table-column prop="accountId" label="账号ID" width="120" align="center"></el-table-column>
      <el-table-column label="照片" width="120" align="center">
        <template #default="scope">
          <el-image 
            v-if="scope.row.photo" 
            :src="getPhotoUrl(scope.row.photo)" 
            style="width: 50px; height: 50px" 
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" align="center"></el-table-column>
      <el-table-column prop="gender" label="性别" width="100" align="center">
        <template #default="scope">{{ scope.row.gender === 'M' ? '男' : '女' }}</template>
      </el-table-column>
      <el-table-column prop="property" label="住址" width="180" align="center"></el-table-column>
      <el-table-column prop="memberType" label="角色" width="120" align="center"></el-table-column>
      <el-table-column prop="contactInfo" label="联系方式" width="150" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="120" align="center"></el-table-column>
      <el-table-column label="操作" width="240" align="center">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" size="mini" @click="openDetails(scope.row)">查看</el-button>
            <el-button type="warning" size="mini" @click="openDetails1(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row type="flex" justify="center" style="margin-top: 20px;">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,50]" 
        :page-size="pageSize" 
        :total="tableData.length"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { post, get } from '@/utils/axios';

// 对话框控制变量
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogVisible2 = ref(false);

// 搜索和分页变量
const searchQuery1 = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const tableData = ref([]);

// 表单引用
const ruleFormRef = ref(null);
const addFormRef = ref(null);

// 编辑时保存原始数据（用于对比修改字段）
const originalRow = ref({});

// 详情数据对象
const userMessage = reactive({
  id: '',
  accountId: '',
  photo: '',
  property: '',
  name: '',
  identityNumber: '',
  contactInfo: '',
  occupation: '',
  birthDate: '',
  gender: '',
  memberType: '',
  remarks: '',
  status: '',
  createdAt: ''
});

// 编辑表单数据（新增originalPhoto保存原始头像）
const ruleForm = reactive({
  id: '',
  accountId: null,
  originalPhoto: null, // 保存原始头像（用于对比是否修改）
  photo: null, // 新上传的头像（base64）
  property: '',
  name: '',
  identityNumber: '',
  contactInfo: '',
  occupation: '',
  birthDate: '',
  gender: '',
  memberType: '',
  remarks: '',
  status: ''
});

// 新增表单数据
const addForm = reactive({
  accountId: null,
  photo: null, // 头像base64
  property: '',
  name: '',
  identityNumber: '',
  contactInfo: '',
  occupation: '',
  birthDate: '',
  gender: '',
  memberType: '',
  remarks: '',
  status: ''
});

// 编辑表单校验规则（可选化）
const rules = reactive({
  name: [
    { 
      validator: (rule, value, callback) => {
        if (!value) callback(); // 不填则通过（保留原值）
        else if (!/^[\u4e00-\u9fa5a-zA-Z]{2,10}$/.test(value)) callback(new Error('姓名需2-10位中英文'));
        else callback();
      }, 
      trigger: 'blur' 
    }
  ],
  identityNumber: [
    { 
      validator: (rule, value, callback) => {
        if (!value) callback(); // 不填则通过
        else if (!/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) callback(new Error('请输入18位有效身份证'));
        else callback();
      }, 
      trigger: 'blur' 
    }
  ],
  contactInfo: [
    { 
      validator: (rule, value, callback) => {
        if (!value) callback(); // 不填则通过
        else if (!/^1[3-9]\d{9}$/.test(value)) callback(new Error('请输入11位有效手机号'));
        else callback();
      }, 
      trigger: 'blur' 
    }
  ],
  gender: [
    { 
      validator: (rule, value, callback) => {
        // 没选性别但原始数据有 → 不修改，通过
        if (!value && originalRow.value.gender) callback();
        else if (value) callback();
        else callback(new Error('请选择性别（若需修改）'));
      }, 
      trigger: 'change' 
    }
  ],
  accountId: [
    { 
      validator: (rule, value, callback) => {
        if (value === null || value === undefined) callback(); // 不填则通过
        else if (!Number.isInteger(value) || value < 0) callback(new Error('请输入非负整数'));
        else callback();
      }, 
      trigger: 'blur' 
    }
  ]
});

// 新增表单校验规则（保持必填字段）
const addRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{2,10}$/, message: '姓名需2-10位中英文', trigger: 'blur' }
  ],
  identityNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入18位有效身份证', trigger: 'blur' }
  ],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效手机号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  accountId: [
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ]
});

// 照片上传处理（编辑）
const handlePhotoChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    ruleForm.photo = e.target.result; // 保存base64（用于预览）
  };
  reader.readAsDataURL(file.raw);
};

// 照片上传处理（新增）
const handleAddPhotoChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    addForm.photo = e.target.result; // 保存base64
  };
  reader.readAsDataURL(file.raw);
};

// base64转Blob（用于FormData提交给后端MultipartFile）
const base64ToBlob = (base64Data) => {
  if (!base64Data || !base64Data.startsWith('data:image')) return null;
  const arr = base64Data.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  const u8arr = new Uint8Array(bstr.length);
  for (let i = 0; i < bstr.length; i++) u8arr[i] = bstr.charCodeAt(i);
  return new Blob([u8arr], { type: mime });
};

// 照片显示处理（支持后端byte[]或base64）
const getPhotoUrl = (photoData) => {
  if (!photoData) return '';
  // 若为base64直接返回
  if (typeof photoData === 'string' && photoData.startsWith('data:image')) return photoData;
  // 若为byte[]转Blob URL
  const blob = new Blob([new Uint8Array(photoData)], { type: 'image/jpeg' });
  return URL.createObjectURL(blob);
};

// 转换表单数据为FormData（编辑时只传修改字段）
const convertToFormData = (form, isEdit = false) => {
  const fd = new FormData();
  if (isEdit) {
    fd.append('id', form.id); // 必传ID
    // 对比原始数据，只传变化的字段
    Object.keys(form).forEach(key => {
      // 跳过原始头像、空值、未修改的字段
      if (key === 'originalPhoto' || !form[key] || JSON.stringify(form[key]) === JSON.stringify(originalRow.value[key])) return;
      
      if (key === 'photo') {
        // 头像：base64转Blob
        const blob = base64ToBlob(form[key]);
        if (blob) fd.append('photo', blob, `avatar_${Date.now()}.${blob.type.split('/')[1]}`);
      } else {
        fd.append(key, form[key]);
      }
    });
  } else {
    // 新增：传所有非空字段
    Object.keys(form).forEach(key => {
      if (!form[key]) return;
      if (key === 'photo') {
        const blob = base64ToBlob(form[key]);
        if (blob) fd.append('photo', blob, `avatar_${Date.now()}.${blob.type.split('/')[1]}`);
      } else {
        fd.append(key, form[key]);
      }
    });
  }
  return fd;
};

// 日期格式化
const formatDate = (dateValue) => {
  if (!dateValue) return '';
  const date = typeof dateValue === 'string' ? new Date(dateValue) : dateValue;
  if (isNaN(date.getTime())) return '';
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  const statusColorMap = { 'Active': 'green-row', 'InActive': 'gray-row' };
  return statusColorMap[row.status] || '';
};

// 打开详情对话框
const openDetails = (row) => {
  dialogVisible.value = true;
  Object.assign(userMessage, row);
};

// 打开编辑对话框（保存原始数据）
const openDetails1 = (row) => {
  dialogVisible1.value = true;
  // 深拷贝原始数据（避免双向绑定）
  originalRow.value = JSON.parse(JSON.stringify(row));
  const temp = JSON.parse(JSON.stringify(row));
  // 保存原始头像，用于对比
  temp.originalPhoto = temp.photo;
  temp.photo = null; // 清空新头像字段
  Object.assign(ruleForm, temp);
};

// 打开新增对话框
const openDetails2 = () => {
  dialogVisible2.value = true;
  // 重置表单
  if (addFormRef.value) addFormRef.value.resetFields();
  Object.keys(addForm).forEach(key => addForm[key] = key === 'gender' ? '' : null);
};

// 分页处理
const handleSizeChange = (val) => { pageSize.value = val; currentPage.value = 1; };
const handleCurrentChange = (val) => { currentPage.value = val; };

// 编辑提交（FormData格式）
const formSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '修改中...' });
    const formData = convertToFormData(ruleForm, true); // 编辑模式
    
    post('/sc/members/update', formData, (res) => {
      loading.close();
      if (res.status === 1) {
        ElMessage.success('修改成功！');
        dialogVisible1.value = false;
        fetchTableData();
      } else {
        ElMessage.error(res.msg || '修改失败');
      }
    }, (err) => {
      loading.close();
      ElMessage.error('请求失败：' + (err.message || '网络异常'));
    }, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  });
};

// 新增提交（FormData格式）
const addSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' });
    const formData = convertToFormData(addForm, false); // 新增模式
    
    post('/sc/members/add', formData, (res) => {
      loading.close();
      if (res.status === 1) {
        ElMessage.success('添加成功！');
        dialogVisible2.value = false;
        // 重置表单
        if (addFormRef.value) addFormRef.value.resetFields();
        Object.keys(addForm).forEach(key => addForm[key] = key === 'gender' ? '' : null);
        fetchTableData();
      } else {
        ElMessage.error(res.msg || '添加失败');
      }
    }, (err) => {
      loading.close();
      ElMessage.error('请求失败：' + (err.message || '网络异常'));
    }, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  });
};

// 搜索处理
// 搜索处理
// 搜索处理
const handleSearch = () => {
  const loading = ElLoading.service({ text: '搜索中...' });
  if (!searchQuery1.value.trim()) {
    fetchTableData();
    loading.close();
    return;
  }
  // 修复参数传递方式，直接传递参数对象，不要嵌套在params中
  get('/sc/members/getByName', { name: searchQuery1.value }, (res) => {
    loading.close();
    if (res.status === 1) {
      tableData.value = res.data;
      ElMessage.success(res.msg);
    } else {
      tableData.value = [];
      ElMessage.warning(res.msg || '未找到匹配记录');
    }
  }, (err) => {
    loading.close();
    ElMessage.error('搜索失败：' + err.message);
  });
};


// 删除处理
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定删除成员【${row.name}】吗？`,
    '删除警告',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(() => {
    const loading = ElLoading.service({ text: '删除中...' });
    // 使用GET请求删除
    get('/sc/members/deleteById', { params: { id: row.id } }, (res) => {
      loading.close();
      if (res.status === 1) {
        ElMessage.success('删除成功！');
        fetchTableData();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    }, (err) => {
      loading.close();
      ElMessage.error('删除失败：' + err.message);
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 获取所有成员数据（使用GET请求）
const fetchTableData = () => {
  const loading = ElLoading.service({ text: '加载中...' });
  get('/sc/members/getAll', {}, (res) => {
    loading.close();
    if (res.status === 1) {
      tableData.value = res.data;
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  }, (err) => {
    loading.close();
    ElMessage.error('加载失败：' + err.message);
  });
};

// 页面挂载时加载数据
onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
.member-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}
.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-table .green-row {
  background-color: #f0f9eb;
}

.el-table .gray-row {
  background-color: #f5f5f5;
}

.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-form-item {
  margin-bottom: 15px;
}

/* 表单提示文字 */
.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>
